package cn.ly.rabbit.rabbitListener;

import cn.ly.rabbit.config.RabbitConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * 死信消息：情况一
 * 监听设置了死信属性的B_Queue队列
 * 但我们收到消息后，拒绝它且不再返回队列：即模拟让该消息成为【死信消息】!!!!!!!!!!!!!!!!!
 */
@Component
@RabbitListener(queues = RabbitConfig.B_Queue_Name)   //这里监听一个叫b.queue的队列，该队列设置了死信交换器和死信路由
public class BQueueListener {

    @RabbitHandler
    public void process(String email, Channel channel, Message message)  {
        try {
            //拿到消息
//            String mm = new String(message.getBody());
            System.out.println("监听到B_Queue消息：>>>>>>>>>>>>>>msg:"+email);
            //...业务逻辑
            //手动确认
//            System.out.println(">>>>>>>>>>>>手动应答后，就不会转发到死信队列上去了");
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);  //第二个参数表示批量确认
            try {
                //我们不确认收到消息，而是拒绝掉该消息，且不用返回队列
                System.out.println(">>>>>>>>>对配置了死信属性的B_Queue队列消息，业务上出错拒绝，并抛弃不反回队列");
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);   //第二个参数表示是否重新返回队列：requeue
            } catch (IOException e1) {
                System.out.println(">>>>>>>>>>>>>>>拒绝报错");
            }
        } catch (Exception e) {
            System.out.println(">>>>>>>>>>>>>>>拒绝任务");
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);   //第二个参数表示是否重新返回队列：requeue
            } catch (IOException e1) {
                System.out.println(">>>>>>>>>>>>>>>拒绝报错");
            }
        }
    }
}
